package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.VideoInfoMapper;
import com.lst.entity.request.ClientMessageReqPara;
import com.lst.entity.response.ClientMessageResPara;
import com.lst.model.MessageReadLog;
import com.lst.model.MstMessage;
import com.lst.model.OnlineCourse;
import com.lst.model.ProjectInfo;
import com.lst.model.VideoInfo;
import com.lst.model.WenwInfo;
import com.lst.service.MessageReadLogService;
import com.lst.service.MstMessageService;
import com.lst.service.OnlineCourseService;
import com.lst.service.ProjectInfoService;
import com.lst.service.WenwInfoService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: MessageListServlet
 * @Description: 官方通知接口
 * @author zmm
 * @date 2017年11月30日 
 * 
 */
public class MessageListServlet extends BaseServlet {

    private static final long serialVersionUID = 1L;

    private MstMessageService mstMessageService = ctx.getBean(MstMessageService.class);
    
    private WenwInfoService wenwInfoService = ctx.getBean(WenwInfoService.class);
    
    private VideoInfoMapper videoInfoMapper = ctx.getBean(VideoInfoMapper.class);
    
    private OnlineCourseService onlineCourseService = ctx.getBean(OnlineCourseService.class);
    
    private ProjectInfoService projectInfoService = ctx.getBean(ProjectInfoService.class); 
    
    private MessageReadLogService messageReadLogService = ctx.getBean(MessageReadLogService.class);

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
	Date startDate = new Date();
	logger.info("doPost begin: " + startDate);

	ClientMessageResPara resPara = new ClientMessageResPara();

	try {
	    ClientMessageReqPara reqPara = getReqPara(request);

	    if (isCheckField(reqPara, resPara)) {
		Integer clientid = Integer.valueOf(reqPara.getUserid());
		Integer page = Integer.valueOf(reqPara.getPage());
		Integer pagesize = Integer.valueOf(reqPara.getPagesize());

		Map<String, Object> cmMap = new HashMap<String, Object>();

		cmMap.put("enabled", true);
		cmMap.put("isDeleted", false);
		cmMap.put("receiveid", clientid);
	//	cmMap.put("type", CommCode.SYSCODE_MSG_TYPE_PUSH);
		cmMap.put("orderByClause", "mm.createdate desc");

		PageBounds pageBounds = new PageBounds(page, pagesize);

		// 查询官方通知列表
		List<MstMessage> mmlist = mstMessageService.queryByList2(cmMap,pageBounds);
		if(mmlist!=null&&mmlist.size()>0){
			for(MstMessage mm:mmlist){
				if(mm.getReserved10()!=null&&mm.getReserved10().contains("=")){
					String strlink=mm.getReserved10();
					String[] strs=strlink.split("=");
					String type=strs[1].split("&")[0];
					String strId=strs[2];
					if(type.equals("wenw")){
						WenwInfo wen=wenwInfoService.selectByPrimaryKey(Integer.valueOf(strId));
						mm.setReserved11(wen.getCover());
					}
					if(type.equals("video")){
						VideoInfo vi = videoInfoMapper.selectByPrimaryKey(Integer.valueOf(strId));
						mm.setReserved11(vi.getReserved9());
					}
					if(type.equals("online_course")){
						OnlineCourse onlineCourse=onlineCourseService.selectByPrimaryKey(Integer.valueOf(strId));
						mm.setReserved11(onlineCourse.getCoverurl());
					}
					if(type.equals("project")){
						ProjectInfo p = projectInfoService.selectByPrimaryKey(Integer.valueOf(strId));
						mm.setReserved11(p.getProbill());
					}
				}
				//判断消息是否读
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("messageId", mm.getId());
				map.put("createUser", clientid);
				MessageReadLog messageReadLog=messageReadLogService.selectByMap(map);
				if(messageReadLog==null){
					MessageReadLog messageReadLog2=new MessageReadLog();
					messageReadLog2.setMessageId(mm.getId());
					messageReadLog2.setIsRead(true);
					messageReadLog2.setCreateUser(clientid);
					messageReadLog2.setCreateDate(startDate);
					messageReadLogService.insert(messageReadLog2);
				}
			}
		}


		resPara.setMmlist(mmlist);
		resPara.setCode(CommCode.M_Y000000);
		resPara.setMessage(CommCode.M_Y000001);
	    }
	} catch (Exception e) {
	    resPara.setCode(CommCode.M_A000000);
	    resPara.setMessage(CommCode.M_SYS0001);

	    logger.error("doPost error: ", e);
	}

	try {
	    response.setContentType("application/json;charset=utf-8");
	    response.setHeader("pragma", "no-cache");
	    response.setHeader("cache-control", "no-cache");

	    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
		    .excludeFieldsWithoutExposeAnnotation().serializeNulls()
		    .create();
	    String jsonResult = gson.toJson(resPara);
	    logger.info(jsonResult);

	    logger.info("ClientMessageListServlet jsonResult: " + jsonResult);

	    PrintWriter out = response.getWriter();
	    out.print(jsonResult);
	    out.flush();
	    out.close();

	    logger.info("doPost end run(s): "
		    + DateUtil.calLastedTime(startDate));
	} catch (Exception e) {
	    resPara.setCode(CommCode.M_A000000);
	    resPara.setMessage(CommCode.M_SYS0003);

	    logger.error("doPost error: ", e);
	}
    }

    @Override
    public ClientMessageReqPara getReqPara(HttpServletRequest request) {

	ClientMessageReqPara reqPara = null;

	try {
	    BaseRequest baseRequest = RequestUtils.getRequestPara(request,
		    new ClientMessageReqPara());

	    reqPara = (ClientMessageReqPara) baseRequest.clone();
	    String userid = request.getParameter("userid");
	    String page = request.getParameter("page");
	    String pagesize = request.getParameter("pagesize");

	    logger.info("reqPara userid: " + userid);
	    logger.info("reqPara page: " + page);
	    logger.info("reqPara pagesize: " + pagesize);

	    reqPara.setUserid(userid);
	    reqPara.setPage(page);
	    reqPara.setPagesize(pagesize);

	} catch (Exception e) {
	    logger.error("getReqPara error: ", e);
	}
	return reqPara;
    }

    @Override
    public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
	boolean flag = false;

	ClientMessageReqPara cmReqPara = (ClientMessageReqPara) reqPara;
	ClientMessageResPara cmResPara = (ClientMessageResPara) resPara;

	if (StringUtils.isEmpty(cmReqPara.getUserid())) {
	    cmResPara.setCode(CommCode.M_A000000);
	    cmResPara.setMessage(CommCode.M_P000002);
	} else if (StringUtils.isEmpty(cmReqPara.getPage())) {
	    cmResPara.setCode(CommCode.M_A000000);
	    cmResPara.setMessage(CommCode.M_P000009);
	} else if (StringUtils.isEmpty(cmReqPara.getPagesize())) {
	    cmResPara.setCode(CommCode.M_A000000);
	    cmResPara.setMessage(CommCode.M_P000010);
	} else {
	    flag = true;
	}
	return flag;
    }
}
